//
//  MyCenterVC.m
//  NewPro
//
//  Created by 何荧红 on 2018/10/1.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "MyCenterVC.h"
#import "MyCenterCell.h"
#import "PersonalCenterViewController.h"
#import "OrderCenterViewController.h"
#import "MessageCenterViewController.h"
#import "AdviceViewController.h"
#import "AboutUsViewController.h"
#import "SettingViewController.h"
#import "MineHeaderView.h"
#import "AddressViewController.h"
#import "ScanIDCardFontViewController.h"
#import "UserModel.h"
#import "MineStore.h"
#import "UserList.h"
#import "InvitePartnerViewController.h"
#import "HomeList.h"
#import "LogisticsStore.h"
#import "NewWalletViewController.h"
#import "CYYServiceViewController.h"
#import "PutForwardRecordViewController.h"
#import "KnowMoreVC.h"
#import "UINavigationBar+handle.h"

#import "MyRedenvelopesVC.h"//我的红包

@interface MyCenterVC ()<UITableViewDelegate,UITableViewDataSource,MineHeaderViewDelegate>

@property (nonatomic, strong) UITableView *TableView;
@property (nonatomic, copy) NSArray *dataArr;
@property (strong, nonatomic) MineHeaderView *headerView;
@property (nonatomic,copy) NSArray *vcArr;
@end

@implementation MyCenterVC

- (NSArray *)dataArr{
    
    if (!_dataArr) {
        
        _dataArr = @[@[@{@"name":@"订单中心",@"image":@"订单中心"},@{@"name":@"收货地址",@"image":@"收货地址"}],@[@{@"name":@"实名认证",@"image":@"实名认证"},@{@"name":@"我的钱包",@"image":@"我的钱包"},@{@"name":@"提现记录",@"image":@"我的提现"},@{@"name":@"我的红包",@"image":@"我的红包"},@{@"name":@"消息中心",@"image":@"消息中心"},@{@"name":@"在线客服",@"image":@"我的客服"}],@[@{@"name":@"了解更多",@"image":@"我的更多"},@{@"name":@"投诉建议",@"image":@"投诉建议"},@{@"name":@"关于我们",@"image":@"关于我们"},@{@"name":@"设置",@"image":@"个人设置"}]];
    }
    
    return _dataArr;
}

- (NSArray *)vcArr{
    
    if (!_vcArr) {
        
        _vcArr = @[@[[OrderCenterViewController class],[AddressViewController class]],@[[ScanIDCardFontViewController class],[NewWalletViewController class],[PutForwardRecordViewController class],[MyRedenvelopesVC class],[MessageCenterViewController class],[CYYServiceViewController class]],@[[KnowMoreVC class],[AdviceViewController class],[AboutUsViewController class],[SettingViewController class]]];
    }
    return _vcArr;
}

- (MineHeaderView *)headerView{
    
    if (!_headerView) {
        
        CGFloat scale = 0.22;
        _headerView = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth * scale)];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController.navigationBar navBarBackGroundColor:BLUECOLOR image:nil isOpaque:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的";
    
    [self initCSS];
    
    [self refresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNoti) name:@"HADNOREADTOMINE" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNoti) name:@"REALNAMEING" object:nil];

}

- (void)reciveNoti{

    [self refresh];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)initCSS{
    self.TableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.TableView registerNib:[UINib nibWithNibName:@"MyCenterCell" bundle:nil] forCellReuseIdentifier:@"MyCenterCellID"];
    self.TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.TableView.showsVerticalScrollIndicator = NO;
    self.TableView.tableHeaderView = self.headerView;
    self.TableView.sectionFooterHeight = 14.5;
    self.TableView.sectionHeaderHeight = 0.5;
    self.TableView.delegate = self;
    self.TableView.dataSource = self;

    MJWeakSelf
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf refresh];
    }];
    
    header.lastUpdatedTimeLabel.hidden = YES;
    self.TableView.mj_header = header;
    
    [self.view addSubview:self.TableView];
    
    if (@available(iOS 11, *)) {

        _TableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; //iOS11 解决SafeArea的问题，同时能解决pop时上级页面scrollView抖动的问题

    }
   
    [self.TableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(0);
    }];
}

- (void)refresh{
    
    MineStore *store = [[MineStore alloc] init];
    
    MJWeakSelf
    [store getUserInfoWithCustomId:[UserDefaultsManager sharedInstance].user_id Success:^(UserModel *model) {
        
        [HomeList sharedInstance].userModel = model;
        [HomeList sharedInstance].hadRealName = model.isSubmitRealNameAuthenticationed;

        [weakSelf.TableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:1], nil] withRowAnimation:UITableViewRowAnimationNone];
    
        [UserList sharedInstance].currentUserModel = model;
    
        NSString *str = [NSString stringWithFormat:@"%@",model.readnum];
        
        [weakSelf.TableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:4 inSection:1], nil] withRowAnimation:UITableViewRowAnimationNone];
        
        if (![str isEqualToString:@"0"] && ![str isEqualToString:@"(null)"]) {
            
            weakSelf.tabBarItem.badgeValue = str;
            
        }else{
            
            weakSelf.tabBarItem.badgeValue = nil;
        }
        
        NSDictionary *dic = [NSDictionary dictionaryWithObject:str forKey:@"info"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"headerTopNewsNum" object:nil userInfo:dic];
        
        [weakSelf.headerView.titleBtn setTitle:model.realName forState:UIControlStateNormal];
        [weakSelf.headerView.phoneBtn setTitle:[NSString stringWithFormat:@"%@****%@",[model.customName substringToIndex:3],[model.customName substringFromIndex:model.customName.length - 4]] forState:UIControlStateNormal];
        [weakSelf.headerView.headIm sd_setImageWithURL:[NSURL URLWithString:model.headImage] placeholderImage:[UIImage imageNamed:@"关于我们logo"]];
        
        [weakSelf.TableView.mj_header endRefreshing];
        
    } Failure:^(NSError *error) {
       
        [weakSelf.TableView.mj_header endRefreshing];
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArr[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCenterCellID"];
    cell.subimg.image = [UIImage imageNamed:self.dataArr[indexPath.section][indexPath.row][@"image"]];
    cell.subtitle.text = self.dataArr[indexPath.section][indexPath.row][@"name"];
    if (indexPath.section == 1 && indexPath.row == 0) {
        cell.conttitle.hidden = NO;
    }else{
        cell.conttitle.hidden = YES;
    }
    if (indexPath.row == [self.dataArr[indexPath.section] count] - 1) {
        cell.line.hidden = YES;
    }else{
        cell.line.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.hadRealName = [HomeList sharedInstance].hadRealName;
    [cell setReadNum:[UserList sharedInstance].currentUserModel.readnum andTiTle:self.dataArr[indexPath.section][indexPath.row][@"name"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
            
            [self pushVC:indexPath];
            break;
        case 1:
            
            switch (indexPath.row) {
                case 0:
                    
                    [self pushRealName];
                    break;
                case 4:
                    
                    [self pushMessageCenter];
                    break;
                default:
                    
                    [self pushVC:indexPath];
                    break;
            }
            break;
        case 2:
            switch (indexPath.row) {
                case 3:
                    
                    [self pushSetting];
                    break;
                    
                default:
                    
                    [self pushVC:indexPath];
                    break;
            }
        default:
            break;
    }
    
}

#pragma mark - 跳转收货地址
- (void)pushAddress{
    
    if (![[HomeList sharedInstance].hadRealName isEqualToString:@"4"]) {
        
        
        return [self goRealNameWithFlag:[HomeList sharedInstance].hadRealName];
    }
    
    AddressViewController *VC = [[AddressViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 实名认证
- (void)pushRealName{
    
    if ([[HomeList sharedInstance].hadRealName isEqualToString:@"4"]) {
        
        return [self showMBPError:@"您已实名认证"];
    }
    
    if ([[HomeList sharedInstance].hadRealName isEqualToString:@"2"]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您已提交实名认证，请耐心等待审核" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"前往修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            ScanIDCardFontViewController *VC = [[ScanIDCardFontViewController alloc] init];
            [VC setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:VC animated:YES];
            
        }]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        return;
    }
    
    
    ScanIDCardFontViewController *VC = [[ScanIDCardFontViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 消息中心
- (void)pushMessageCenter{
    
    MessageCenterViewController *VC = [[MessageCenterViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 设置
- (void)pushSetting{
    
    SettingViewController *VC = [[SettingViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - MineHeaderViewDelegate

#pragma mark - 头像
-(void)onHeaderIm{
    
    [self goPerson];
}

#pragma mark - 标题
- (void)onTitleBtn:(UIButton *)btn{
    
    [self goPerson];
}

#pragma mark - 电话号码
- (void)onPhoneBtn:(UIButton *)btn{
    
    [self goPerson];
}

- (void)goPerson{
    
    PersonalCenterViewController *VC = [[PersonalCenterViewController alloc] init];
    MJWeakSelf
    [VC setImgUpBlock:^(NSString *imgUrl) {
        
        [UserList sharedInstance].currentUserModel.headImage = imgUrl;
        
        [weakSelf.headerView.headIm sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"头像"]];
        
    }];
    
    
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 二维码
- (void)onCodeBtn:(UIButton *)btn{
    
    if (![[HomeList sharedInstance].hadRealName isEqualToString:@"4"]) {
        
        
        return [self goRealNameWithFlag:[HomeList sharedInstance].hadRealName];
    }
    
    InvitePartnerViewController *VC = [[InvitePartnerViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];

}


#pragma mark - 前往实名认证
- (void)goRealNameWithFlag: (NSString *)flag{
    
    NSString *mes = @"您尚未进行实名认证";
    NSString *title = @"前往认证";
    if ([flag isEqualToString:@"2"]) {
        
        mes = @"您已提交实名认证，请耐心等待审核";
        title = @"前往修改";
    }
    
    if ([flag isEqualToString:@"3"]) {
        
        mes = @"实名认证未通过，请重新实名认证";
        title = @"重新认证";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:mes preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        ScanIDCardFontViewController *VC = [[ScanIDCardFontViewController alloc] init];
        [VC setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:VC animated:YES];
        
    }]];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

- (void)pushVC:(NSIndexPath *)indexPath{
    
    if (![[HomeList sharedInstance].hadRealName isEqualToString:@"4"]) {
        
        
        return [self goRealNameWithFlag:[HomeList sharedInstance].hadRealName];
    }
    
    UIViewController *VC = [[self.vcArr[indexPath.section][indexPath.row] alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
    
}
@end
